package com.wj.gulimall.product.exception;

import com.wj.common.exception.BizCodeEnum;
import com.wj.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.wj.gulimall.product.app")
public class GulimallExceptionControllerAdvice {

    /**
     * 处理数据校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new LinkedHashMap<>();
        bindingResult.getFieldErrors().forEach(err -> {
            map.put(err.getField(), err.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION).addData(map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        throwable.printStackTrace();
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION);
    }
}
